package com.xiaomi.front.controller;

import com.xiaomi.front.service.user.UserService;
import com.xiaomi.util.FrontUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@Controller
public class RegController {

    @Autowired
    private UserService userService;

    //用户注册
    @PostMapping("/front_RegUser")
    public String RegUser(String phone, String password, String code, Model model, HttpSession session) {
        //获取session中的验证码
        String code_key = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        //移除session验证码
        session.removeAttribute(KAPTCHA_SESSION_KEY);

        if (code.equals(code_key)) {
            String username = FrontUtil.Username();
            int result = userService.RegUser(phone, password, username);
            if (result == 1) {
                return "front/index";
            } else {
                model.addAttribute("regerr", "该手机号已存在！");
                return "forward:/reg.jsp";
            }
        } else {
            model.addAttribute("regerr", "验证码不正确！！");
            return "forward:/reg.jsp";
        }

    }
}
